<?php
/**
 *
 * @author fanzhanao
 * @version 
 */
class cartoon_model_tag extends cartoon_model_bmodel{
	
	public function __construct(){
    	parent::__construct();
        $this->table = 'cartoon_tags';
        $this->tb_rel	=	'cartoon_tags_rel';
    }
    
    /**
     * 添加tag
     *
     * @param unknown_type $tagname
     * @return unknown
     */
    public function addTag($tagname){
    	if(!trimAll($tagname)) return false;
    	//检查是否已经使用过了
    	if($id = $this->chkTag($tagname)){//如果已经使用过了
    		//更新相应的tag使用次数
    		$this->upNums($id);
    		return $id;
    	}
    	//如果没有使用过，则添加之
    	$para['tag_name']	=	$tagname;
    	$para['tag_type']	=	$para['tag_nums']	=	1;
    	$para['tag_add_time']	=	CURRENT_TIME;
    	return $this->db->insert($this->table,$para);
    }
    
    /**
     * 删除tag
     *
     * @param unknown_type $tagid
     */
    public function delTag($tagid){
    	$tagid = is_array($tagid)?implode(',',$tagid):$tagid;
    	$sql = "DELETE FROM $this->table WHERE tag_id IN ($tagid)";
    	if($this->db->query($sql)){
    		$this->db->query("DELETE FROM $this->tb_rel WHERE tag_id IN ($tagid)");
    		return true;
    	}
    }
    
    /**
     * 根据资源id删除所有该资源和tag的关系
     *
     * @param unknown_type $resid
     */
    public function removeRel($resid,$tag_id = null){
    	$sql = "DELETE FROM $this->tb_rel WHERE res_id = $resid ";
    	if($tag_id) $sql.=' AND tag_id = '.$tag_id;
    	
    	return $this->db->query($sql);
    }
    
    /**
     * 添加关系
     *
     * @param  int $tagid
     * @param   int $resid
     */
    public function addRel($tagid,$resid){
    	if(!($tagid && $resid)) return false;
    	return $this->db->query("INSERT INTO $this->tb_rel VALUES(NULL,$tagid,$resid,1,".CURRENT_TIME.')');
    }
    /**
     * 检查tag是否已经被使用了
     *
     * @param unknown_type $tagname
     */
    public function chkTag($tagname){
    	return $this->db->fetchField("SELECT tag_id FROM $this->table WHERE tag_name = $tagname ",'tag_id');
    }
    
    /**
     * 更新tag使用次数
     *
     * @param unknown_type $tagid
     * @return unknown
     */
    public function upNums($tagid){
    	return $this->db->query("UPDATE $this->table SET tag_nums = tag_nums+1 WHERE tag_id = $tagid");
    }
    
    /**
     * 根据tag，检索tag对应的资源id
     *
     * @param unknown_type $tag
     */
    public function getResList($tag){
    	$return  = array();
    	if($tag){
    		if($rs = $this->db->fetchAll("SELECT a.res_id as id FROM $this->tb_rel a,$this->table b WHERE a.tag_id = b.tag_id AND b.tag_name = '$tag'") ){
    			while ($row = current($rs)) {
    				array_push($return,$row['id']);
    				next($rs);
    			}
    		}
    	}
    	return $return;
    }
    
}
?>